java script and dom manipulationJavaScript is the powerhouse behind interactive and dynamic websites. Whether it's animating a button, updating content dynamically, or creating entire web applications, JavaScript has your back. ๐ช
JavaScript is a versatile, high-level programming language used to control the behavior of web pages. When combined with HTML and CSS, it enables web developers to build interactive and responsive websites.
Think of it as the brain ๐ง of your website, while HTML is the skeleton and CSS is the skin and makeup.
Variables act like containers that hold data values.
// Declaring Variables
let playerName = "Eddy"; // Can change
const MAX_LEVEL = 10; // Constant value
var score = 0; // Avoid using var in modern JS
// Primitive Data Types
let greeting = "Hello, World!";
let age = 25;
let pi = 3.14;
let isRaining = false;
let emptyValue = null;
let notAssigned;
// Non-Primitive Data Types
let user = { name: "Eddy", age: 25, role: "Developer" };
let colors = ["red", "blue", "green"];
Operators are special symbols that perform actions on values or variables.
let a = 10, b = 5;
console.log(a + b); // 15
console.log(a - b); // 5
console.log(a * b); // 50
console.log(a / b); // 2
console.log(a % b); // 0
let x = 10;
x += 5; // 15
x *= 2; // 30
let a = 5;
let b = "5";
console.log(a == b); // true
console.log(a === b); // false
console.log(10 > 5); // true
let isAdult = true;
let hasID = false;
console.log(isAdult && hasID); // false
console.log(isAdult || hasID); // true
console.log(!isAdult); // false
let greeting = "Hello";
greeting += ", World!";
console.log(greeting); // Hello, World!
console.log(typeof "Hello"); // string
console.log([] instanceof Array); // true
let x = (2, 3); // x is 3
console.log(x);
let name = null;
let defaultName = name ?? "Guest";
console.log(defaultName); // Guest
Functions make your code reusable and easier to maintain. Below, you can edit the example and click Run to see it in action!
Edit the code below and click Run to see how functions work.
Loops are one of the most powerful tools in JavaScript. They allow us to execute a block of code repeatedly, saving time and effort. Imagine you need to print numbers from 1 to 100โdoing it manually would be exhausting! Loops let you automate this process, making your code efficient and concise.
So, buckle up as we explore loops in JavaScript, step by step, with plenty of examples to make learning fun! ๐
for loop, while loop, do...while loop, for...in loop, for...of loop
The for loop repeats a block of code a specific number of times.
Syntax:
for (initialization; condition; increment/decrement) { /* code */ }
Example: Counting from 1 to 5
for (let i = 1; i <= 5; i++) {
console.log(`Count: ${i}`);
}
Continues as long as the specified condition is true.
Example: Printing numbers until 5
let num = 1;
while (num <= 5) {
console.log(`Number: ${num}`);
num++;
}
Runs at least once, then repeats while the condition is true.
Example:
let count = 6;
do {
console.log(`Count: ${count}`);
count++;
} while(count <= 5);
Used to iterate over object properties.
Example:
const person = { name: "Eddy", age: 25, role: "Instructor" };
for (let key in person) {
console.log(`${key}: ${person[key]}`);
}
Used to iterate over arrays or strings.
Example:
const fruits = ["๐", "๐", "๐"];
for (let fruit of fruits) {
console.log(`I love ${fruit}`);
}
break: Exits the loop entirely.
continue: Skips the current iteration and moves to the next.
Example:
for (let i = 1; i <= 5; i++) {
if(i===3) continue;
if(i===5) break;
console.log(i);
}
Loops inside loops for multi-level tasks like multiplication tables.
Example:
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(`${i} x ${j} = ${i*j}`);
}
}
String Example:
const name = "Eddy";
for(let char of name){
console.log(char);
}
Array Example:
const numbers = [10,20,30];
for(let num of numbers){
console.log(num);
}
If the loop condition never becomes false, the loop runs forever. Be cautious!
The Document Object Model (DOM) is the foundation of every modern web page. It allows JavaScript to interact with HTML and CSS dynamically. In this guide, weโll explore what the DOM is, how to select elements, and how to manipulate them to create interactive websites. ๐
The DOM represents an HTML document as a tree of objects. These nodes can be:
<div>, <h1>, <p>, etc.id, class, etc.Think of the DOM as a bridge between HTML and JavaScript. With JS, you can select elements, modify content or styles, and respond to user interactions.
Example HTML:
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Welcome</h1>
<p>Hello, World!</p>
<button>Click Me</button>
</body>
</html>
DOM Tree:
Use document.getElementById("id") to select a single element.
<h1 id="title">Hello, DOM!</h1>
<script>
const title = document.getElementById("title");
console.log(title.textContent); // Hello, DOM!
</script>
Use document.getElementsByClassName("className").
<p class="intro">Welcome!</p>
<p class="intro">Let's learn the DOM.</p>
<script>
const intros = document.getElementsByClassName("intro");
console.log(intros[0].textContent); // Welcome!
</script>
Use document.getElementsByTagName("tagName").
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<script>
const paragraphs = document.getElementsByTagName("p");
console.log(paragraphs.length); // 2
</script>
Modern and versatile methods:
document.querySelector("selector"); // first match
document.querySelectorAll("selector"); // all matches (NodeList)
Example:
<p id="info" class="highlight">Hello!</p>
<script>
const info = document.querySelector("#info");
console.log(info.textContent); // Hello!
</script>
<p class="highlight">One</p>
<p class="highlight">Two</p>
<script>
const highlights = document.querySelectorAll(".highlight");
highlights.forEach(el => console.log(el.textContent)); // One, Two
</script>
<h1 id="title">Old Title</h1>
<script>
const title = document.getElementById("title");
title.textContent = "New Title";
</script>
<div id="container"></div>
<script>
const container = document.getElementById("container");
container.innerHTML = "<p>Dynamic Content</p>";
</script>
<img id="image" src="placeholder.jpg">
<script>
const image = document.getElementById("image");
image.setAttribute("src", "new-image.jpg");
</script>
<p id="text">Style Me!</p>
<script>
const text = document.getElementById("text");
text.style.color = "blue";
text.style.fontSize = "20px";
</script>
<p id="text" class="highlight">Styled Text</p>
<script>
const text = document.getElementById("text");
text.classList.add("bold");
text.classList.remove("highlight");
</script>
<p id="message">Click the button to change me!</p>
<button id="btn">Click Me</button>
<script>
const button = document.getElementById("btn");
const message = document.getElementById("message");
button.addEventListener("click", () => {
message.textContent = "You clicked the button!";
});
</script>
<ul id="list"></ul>
<button id="add">Add Item</button>
<script>
const list = document.getElementById("list");
const addButton = document.getElementById("add");
addButton.addEventListener("click", () => {
const newItem = document.createElement("li");
newItem.textContent = "New Item";
list.appendChild(newItem);
});
</script>
Events are actions that occur on a webpage, such as clicks, keypresses, or mouse movements.
Example: Listening for a Click Event
<button id="alert">Show Alert</button>
<script>
const alertButton = document.getElementById("alert");
alertButton.addEventListener("click", () => {
alert("Button clicked!");
});
</script>
By mastering the DOM, you can create dynamic, interactive, and user-friendly websites. Happy coding! ๐
Hereโs a curated list of websites, videos, and tutorials to help you learn JavaScript and DOM manipulation in-depth. These resources cater to beginners and intermediate learners while providing hands-on experience.
Introduction to the DOM, JavaScript Basics
JavaScript Tutorial, DOM Tutorial
Document and Events
JavaScript Algorithms and Data Structures
An Introduction to DOM Manipulation
You can use AI to explore more about JavaScript and DOM. Examples:
"Explain DOM manipulation with examples."
"What are the differences between querySelector and getElementById in JavaScript?"
"Write a JavaScript script to create and delete elements dynamically in the DOM."
"How can I handle form validation errors in real-time using JavaScript?"
"Explain the event propagation model (bubbling and capturing) with code examples."
"What are the best practices for handling large numbers of DOM elements?"
"Why is my JavaScript click event listener not working on dynamically added elements?"
"How can I improve the performance of my DOM manipulation script?"